import { addLabel, allLabel, deleteLabel, updateLabel } from '@/services/labels'
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons'
import type { ActionType, ProColumns } from '@ant-design/pro-components'
import {
  ModalForm,
  ProForm,
  ProFormText,
  ProTable,
  TableDropdown,
} from '@ant-design/pro-components'
import {
  Button,
  ColorPicker,
  Dropdown,
  Form,
  GetProp,
  message,
  Modal,
  Popconfirm,
  PopconfirmProps,
  Space,
  Tag,
} from 'antd'
import { Color, ColorPickerProps } from 'antd/es/color-picker'
import React, { act } from 'react'
import { useRef, useState } from 'react'
import request from 'umi-request'

export default () => {
  //模态框
  type Color = Extract<
    GetProp<ColorPickerProps, 'value'>,
    string | { cleared: any }
  >
  type Format = GetProp<ColorPickerProps, 'format'>
  const [form] = Form.useForm<{ name: string; company: string }>()
  const [colorHex, setColorHex] = useState<Color>('#1677ff')
  const [formatHex, setFormatHex] = useState<Format | undefined>('hex')

  const hexString = React.useMemo<string>(
    () => (typeof colorHex === 'string' ? colorHex : colorHex?.toHexString()),
    [colorHex]
  )
  //删除逻辑
  const confirm: PopconfirmProps['onConfirm'] = async (values) => {
    await deleteLabel({ labelId: values?.id })
    actionRef.current?.reload()
    message.success('Click on Yes')
  }
  //停用逻辑
  const stop = async (values) => {
    await updateLabel({
      id: values.id,
      status: values.status ? 0 : 1,
      name: values.name,
      color: values.color,
    })
    actionRef.current?.reload()
    message.success('Click on Yes')
  }

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    message.error('Click on No')
  }

  const [dataSource, setDataSource] = useState([])
  const [pageSize, setPageSize] = useState(10)

  const columns: ProColumns[] = [
    {
      dataIndex: 'index',
      key: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '标签名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      tooltip: '标题过长会自动收缩',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '颜色',
      dataIndex: 'color',
      key: 'color',
      align: 'center',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      render: (_, record) => <Tag color={record?.color}>{record?.color}</Tag>,
    },
    {
      disable: true,
      title: '状态',
      width: '10vw',
      dataIndex: 'status',
      key: 'status',
      filters: true,
      onFilter: true,
      editable: false,
      ellipsis: true,
      valueType: 'select',
      valueEnum: {
        all: { text: '全部' },
        false: {
          text: '未启用',
          status: 'Error',
        },
        true: {
          text: '已启用',
          status: 'Success',
        },
      },
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: '10vw',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={(values) => {
            action?.startEditable?.(record.id)
          }}>
          编辑
        </a>,
        <Popconfirm
          // title="Delete the task"
          description="是否确定停用"
          onConfirm={() => stop(record)}
          onCancel={cancel}
          okText="确定"
          cancelText="取消">
          <a target="_blank" rel="noopener noreferrer" key="view">
            {record.status ? '停用' : '启用'}
          </a>
        </Popconfirm>,
        <Popconfirm
          // title="Delete the task"
          description="是否确定删除"
          onConfirm={() => confirm(record)}
          onCancel={cancel}
          okText="确定"
          cancelText="取消">
          <a target="_blank" rel="noopener noreferrer" key="view">
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ]

  const actionRef = useRef<ActionType>()
  return (
    <ProTable
      columns={columns}
      actionRef={actionRef}
      dataSource={dataSource}
      cardBordered
      request={async (values: any) => {
        const result = await allLabel(values)
        setDataSource(result?.data?.records)
        // setDataSource(result?.data)
      }}
      editable={{
        type: 'multiple',
        onSave: async (rowKey, record) => {
          // 这里编写发送请求的逻辑
          const response = await updateLabel(record)
          if (response.success) {
            // 请求成功，更新状态或提示用户
            actionRef.current?.reload()
            message.success('保存成功')
          } else {
            // 处理错误情况
            actionRef.current?.reload()
            message.error('保存失败')
          }
        },
        onDelete: async (rowKey, record) => {
          const response = await deleteLabel({ labelId: record?.id })
          if (response.success) {
            // 请求成功，更新状态或提示用户
            actionRef.current?.reload()
            message.success('删除成功')
          } else {
            // 处理错误情况
            actionRef.current?.reload()
            message.error('删除失败')
          }
        },
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      form={{
        // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.createTime, values.endTime],
            }
          }
          return values
        },
      }}
      pagination={{
        pageSize: pageSize,
      }}
      dateFormatter="string"
      headerTitle="高级表格"
      toolBarRender={() => [
        <ModalForm<{
          name: string
        }>
          width="20vw"
          title="新建标签"
          trigger={
            <Button type="primary">
              <PlusOutlined />
              新建
            </Button>
          }
          form={form}
          autoFocusFirstInput
          modalProps={{
            destroyOnClose: true,
          }}
          submitTimeout={500}
          onFinish={async (values) => {
            const result = await addLabel({
              name: values?.name,
              color: hexString,
            })
            message.success('提交成功')
            actionRef.current?.reload()
            return true
          }}>
          <ProForm.Group>
            <ProFormText
              width="md"
              name="name"
              label="标签名称"
              tooltip="最长为 8 位"
              placeholder="请输入标签名称"
            />
            <ProForm.Item name="color" label="颜色">
              <ColorPicker
                format={formatHex}
                value={colorHex}
                onChange={setColorHex}
                onFormatChange={setFormatHex}
              />
            </ProForm.Item>
          </ProForm.Group>
        </ModalForm>,
      ]}
    />
  )
}
